<template>
  <view class="">
    <CustomNavbar title="用户登录" :left-icon="false"></CustomNavbar>
    <basic-components />
    <view v-if="!loading" class="login-form">
      <!-- 睿赛珂生产管理系统 -->
      <view class="head">
        <view class="img">
          <image src="@/assets/logo.png" />
        </view>
        睿赛珂生产管理系统
      </view>
      <uni-forms ref="userForm" label-position="left" :model-value="userInfo" :rules="rules">
        <uni-forms-item prop="username" border-bottom>
          <uni-easyinput
            v-model="userInfo.username"
            :placeholder-style="placeholderStyle"
            placeholder="请输入账号"
            :input-border="false"
          />
        </uni-forms-item>

        <uni-forms-item prop="password" border-bottom>
          <uni-easyinput
            v-model="userInfo.password"
            :placeholder-style="placeholderStyle"
            type="password"
            placeholder="请输入密码"
            :input-border="false"
            @confirm="login"
          />
        </uni-forms-item>

        <view class="agreement">
          <view class="relative">
            <u-checkbox-group>
              <u-checkbox
                v-model="userInfo.agreement"
                :active-color="globalStore.basicColor.primary"
                size="16px"
                checked
                :name="true"
                @change="checkboxChange"
              />
            </u-checkbox-group>
            <view v-if="userInfo.agreementTooltip" class="tooltip">
              <view />
              <text class="text"> 请先阅读并同意协议 </text>
            </view>
          </view>
          <view class="agreement-text" :class="userInfo.isShake ? 'shake' : ''" @tap="checkboxChange(!userInfo.agreement)">
            我已阅读并同意
            <text v-for="item in agreementOp" :key="item.name" class="path"> 《 {{ item.name }} 》 </text>、
            并授权本系统使用本系统账户信息(如昵称、头像)进行同意管理
          </view>
        </view>

        <view class="btn">
          <u-button
            :class="isActiveBtn ? 'login-btn-activate' : 'login-btn'"
            :disabled="!isActiveBtn"
            text="登 录"
            @tap="login"
          />
          <!-- #ifdef WEB -->

          <view class="qw-box">
            <text class="tag"> 或通过一下方式登录 </text>
            <view class="qiwei">
              <a href="http://mes.cnrecyc.com/api/auth/wxAuth/login"><view class="iconfont icon-qiwei" /></a>
            </view>
          </view>
          <!-- #endif -->
        </view>
      </uni-forms>
    </view>
  </view>
</template>
<script setup lang="ts" name="">
const globalStore = useGlobalStore();
const userStore = useUserStore();

onBeforeMount(() => {
  userInfo.username = uni.getStorageSync("login_name") || "";
  getCode();
});

const agreementOp = [
  {
    name: "用户协议",
    path: ""
  },
  {
    name: "隐私政策",
    path: ""
  }
];
const rules = {
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: ["blur"]
    }
  ]
};

const placeholderStyle = `fontSize:16px;`;

let loading = ref(false);
let code = ref();
const userInfo = reactive({
  username: "",
  password: "",
  verificationCode: "",
  // 协议是否勾选
  agreement: true,
  // 是否使用震动动画
  isShake: false,
  // 协议未勾选提示框是否显示
  agreementTooltip: false,
  time: null
});

const isActiveBtn = computed(() => {
  if (!userInfo.username || !userInfo.password) {
    return false;
  }
  return true;
});

const getCode = async () => {
  code.value = await urlSearch();

  if (code.value) {
    loading.value = true;
    userStore.setToken("");
    try {
      const data = await wxAuthGetUser({ code: code.value });
      const { token, userObj } = data;
      const { username: name } = userObj;
      uni.setStorageSync("login_name", name);
      userStore.setToken(token);
      userStore.setUserInfo(userObj);

      // 获取用户权限
      const auth = await userGetAuthBySysUser({ username: name });
      useAuthStore().getAuthBySysUser(auth);

      loading.value = false;
      uni.redirectTo({
        url: "/pages/home/index"
      });
    } catch (error) {
      loading.value = false;
    }
  }
};

const urlSearch = () => {
  const str = location?.href; // 取得整个地址栏
  if (str && str.indexOf("code=") === -1) {
    return "";
  }
  return location?.href;
};

const login = async () => {
  const { agreement } = userInfo;
  if (!agreement) {
    Object.assign(userInfo, {
      isShake: true,
      agreementTooltip: true
    });
    clearTimeout(userInfo.time);
    setTimeout(() => {
      userInfo.isShake = false;
    }, 500);
    userInfo.time = setTimeout(() => {
      userInfo.agreementTooltip = false;
    }, 2000);
  }

  userStore.setToken("");
  const { username, password } = userInfo;
  try {
    const data = await loginCheck({ username, password });
    const { token, userObj } = data;
    uni.setStorageSync("login_name", username);
    userStore.setToken(token);
    userStore.setUserInfo(userObj);

    // 获取用户权限
    const auth = await userGetAuthBySysUser({ username });
    useAuthStore().getAuthBySysUser(auth);

    uni.redirectTo({
      url: "/pages/home/index"
    });
  } catch (error) {
    console.log();
  }
};
const checkboxChange = (flag: boolean) => {
  userInfo.agreement = flag;
};
</script>
<style lang="scss" scoped src="./login.scss"></style>
<style lang="scss">
.login-form {
  :deep(.uni-input-input) {
    font-size: 18px !important;
    font-weight: bold !important;
  }
}
</style>
